package com.learn.concurrent;

import java.time.LocalDateTime;
import java.util.StringJoiner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxing
 * @version 2020/8/3 5:55 Administrator
 */
public class CreateExecutor {
    public static final int CORE_POOL_SIZE = 5;
    public static final int MAXIMUM_POOL_SIZE = 10;
    public static final int KEEP_ALIVE_TIME = 1;

    class MyThread extends Thread{
        private String command;
        public MyThread(String command) {
            this.command = command;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" start time =" + LocalDateTime.now().toString());
            processCommand();
            System.out.println(Thread.currentThread().getName()+" end time =" + LocalDateTime.now().toString());
        }
        private void processCommand(){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return new StringJoiner(", ", MyThread.class.getSimpleName() + "[", "]")
                    .add("command='" + command + "'")
                    .toString();
        }
    }
    public static void main(String[] args) {
        ThreadPoolExecutor executor =
                new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
                        KEEP_ALIVE_TIME,
                        TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(100)
                ,new ThreadPoolExecutor.CallerRunsPolicy());
        CreateExecutor createExecutor = new CreateExecutor();
        for (int i = 0; i < 10; i++) {
            MyThread thread = createExecutor.new MyThread("i="+i);
            executor.execute(thread);
            System.out.println("线程池中线程数目："+executor.getPoolSize()+"，队列中等待执行的任务数目："+
                    executor.getQueue().size()+"，已执行玩别的任务数目："+executor.getCompletedTaskCount());
        }
        executor.shutdown();
//        while (!executor.isTerminated()){
//            System.out.println("finished all thread");
//        }

    }
}
